package com.lemon.stock.compose

import android.app.DatePickerDialog
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.saveable.autoSaver
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.lemon.stock.R
import com.lemon.stock.app.StockHandleType
import com.lemon.stock.entity.Stock
import com.lemon.stock.theme.cancelColor
import com.lemon.stock.viewmodel.TradeViewModel
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.*

/**
 * 买入的操作，
 */
@Composable
fun StockBuyContent(handleStatus: MutableState<String>, vStock: Stock){
    val mViewModel: TradeViewModel = viewModel()
    val c = Calendar.getInstance()
    var buyDate = remember { mutableStateOf(c) }
    var buyPrice by remember { mutableStateOf(TextFieldValue(vStock.stockPrice.toString())) }
    var buyAmount by remember { mutableStateOf(TextFieldValue("")) }
    var buyCommission by remember { mutableStateOf(TextFieldValue("")) }
    var buyTransfer by remember { mutableStateOf(TextFieldValue("")) }
    val sdfDate = SimpleDateFormat("yyyy 年 MM 月 dd 日")
    val context = LocalContext.current
    val finished = mViewModel.finished.observeAsState(false)
    fun autoData(){
        if(buyPrice.text == "" || buyAmount.text == ""){
            return
        }
        val df = DecimalFormat("######0.00")
        val commissionRatio = 0.0003F
        val transferRatio = 0.00002F
        val total = buyPrice.text.toFloat()*buyAmount.text.toInt()
        var commissionMoney: Float = total*commissionRatio
        var transferMoney = 0F
        if(commissionMoney<5){
            commissionMoney = 5F
        }
        if(vStock.stockExchange == "sh"){
            transferMoney = total*transferRatio
        }
        buyCommission = TextFieldValue(df.format(commissionMoney))
        buyTransfer = TextFieldValue(df.format(transferMoney))
    }
    if(finished.value){
        handleStatus.value = StockHandleType.Detail
        mViewModel.finishReset()
    }else{
        LazyColumn(
            modifier = Modifier.fillMaxSize().padding(16.dp)
        ) {
            val strCaption = context.getResources().getString(R.string.btn_buy)

            val datePickerDialog = DatePickerDialog(
                context,
                DatePickerDialog.OnDateSetListener{ view, year, month, dayOfMonth ->
                    var date = Calendar.getInstance()
                    date.set(Calendar.YEAR, year)
                    date.set(Calendar.MONTH, month)
                    date.set(Calendar.DAY_OF_MONTH, dayOfMonth)
                    buyDate.value = date
                },
                buyDate.value.get(Calendar.YEAR), buyDate.value.get(Calendar.MONTH),buyDate.value.get(
                    Calendar.DAY_OF_MONTH)
            )

            //买入日期
            item{
                Row(){
                    OutlinedTextField(
                        value = TextFieldValue(text=sdfDate.format(buyDate.value.time)),
                        modifier = Modifier.fillMaxSize().padding(vertical = 4.dp),
                        label = { Text(text =strCaption+ stringResource(id = R.string.text_date)) },
                        trailingIcon = {
                            IconButton(onClick = {datePickerDialog.show() }) {
                                Icon(painter = painterResource(id = R.drawable.ic_btn_date), contentDescription = null)
                            }
                        },
                        onValueChange = {autoData()},
                        maxLines = 1,
                        readOnly = true,
                        singleLine = true,
                    )
                }
            }

            //买入价格
            item {
                InputItem(
                    textFieldValue = buyPrice,
                    label = strCaption+ stringResource(id = R.string.text_price),
                    keyboardType = KeyboardType.Number,
                    onTextChanged = {
                        buyPrice = it
                        autoData()
                    },
                    modifier = Modifier.fillMaxSize().padding(vertical = 4.dp)
                )
            }
            //买入数量
            item {
                InputItem(
                    textFieldValue = buyAmount,
                    label = strCaption+ stringResource(id = R.string.text_amount),
                    keyboardType = KeyboardType.Number,
                    onTextChanged = {
                        buyAmount = it
                        autoData()
                    },
                    modifier = Modifier.fillMaxSize().padding(vertical = 4.dp)
                )
            }
            //佣金
            item {
                InputItem(
                    textFieldValue = buyCommission,
                    label = stringResource(id = R.string.stock_commission),
                    keyboardType = KeyboardType.Number,
                    onTextChanged = { buyCommission = it },
                    modifier = Modifier.fillMaxSize().padding(vertical = 4.dp)
                )
            }
            //过户费
            item {
                InputItem(
                    textFieldValue = buyTransfer,
                    label = stringResource(id = R.string.stock_transfer),
                    keyboardType = KeyboardType.Number,
                    onTextChanged = { buyTransfer = it },
                    modifier = Modifier.fillMaxSize().padding(vertical = 4.dp)
                )
            }
            item {
                Row(modifier = Modifier.padding(top = 8.dp)){
                    //取消
                    Button(
                        onClick = {
                            handleStatus.value = StockHandleType.Detail
                        },
                        colors = ButtonDefaults.buttonColors(
                            backgroundColor = cancelColor,
                            contentColor = Color.White
                        ),
                        modifier = Modifier.weight(1f).padding(horizontal = 8.dp)

                    ) {
                        Text(
                            text = stringResource(id = R.string.btn_cancel),
                            color = MaterialTheme.colors.onPrimary,
                            modifier = Modifier.padding(horizontal = 30.dp, vertical = 8.dp)
                        )
                    }
                    //买入
                    Button(
                        onClick = {
                            mViewModel.tradeBuy(
                                stock = vStock,
                                price = buyPrice.text.toFloat(),
                                amount = buyAmount.text.toInt(),
                                date = buyDate.value,
                                commission = buyCommission.text.toFloat(),
                                transfer = buyTransfer.text.toFloat()
                            )
                        },
                        modifier = Modifier.weight(1f).padding(horizontal = 8.dp)
                    ) {
                        Text(
                            text = strCaption,
                            color = MaterialTheme.colors.onPrimary,
                            modifier = Modifier.padding(horizontal = 30.dp, vertical = 8.dp)
                        )
                    }
                }

            }
        }
    }

}

/**
 * 股票卖出
 */
@Composable
fun StockSellContent(handleStatus: MutableState<String>, vStock: Stock){

    val mViewModel: TradeViewModel = viewModel()
    val c = Calendar.getInstance()
    var sellDate = remember { mutableStateOf(c) }
    var sellPrice by remember { mutableStateOf(TextFieldValue(vStock.stockPrice.toString())) }
    var sellAmount by remember { mutableStateOf(TextFieldValue("")) }
    var sellCommission by remember { mutableStateOf(TextFieldValue("")) }
    var sellTransfer by remember { mutableStateOf(TextFieldValue("")) }
    var sellTax by remember { mutableStateOf(TextFieldValue("")) }
    var bonusTax by remember { mutableStateOf(TextFieldValue(""))}
    val sdfDate = SimpleDateFormat("yyyy 年 MM 月 dd 日")
    val context = LocalContext.current
    val stocks = mViewModel.finished.observeAsState(false)

    fun autoData(){
        if(sellAmount.text =="" || sellPrice.text == ""){
            return
        }
        if(sellAmount.text.toInt()>vStock.holdStock){
            sellAmount = TextFieldValue(vStock.holdStock.toString())
        }
        val df = DecimalFormat("######0.00")
        val commissionRatio = 0.0003F
        val transferRatio = 0.00002F
        val taxRatio = 0.001F
        val total = sellPrice.text.toFloat()*sellAmount.text.toInt()
        var commissionMoney: Float = total*commissionRatio
        var transferMoney = 0F
        val taxMoney: Float = total*taxRatio
        if(commissionMoney<5){
            commissionMoney = 5.00F
        }
        if(vStock.stockExchange == "sh"){
            transferMoney = total*transferRatio
        }
        sellCommission = TextFieldValue(df.format(commissionMoney))
        sellTransfer = TextFieldValue(df.format(transferMoney))
        sellTax = TextFieldValue(df.format(taxMoney))
        bonusTax = TextFieldValue(df.format(mViewModel.bonusTax(vStock, sellAmount.text.toInt(), sellDate.value)))
    }

    if(stocks.value){
        handleStatus.value = StockHandleType.Detail
        mViewModel.finishReset()
    }else{
        LazyColumn(
            modifier = Modifier.fillMaxSize().padding(16.dp)
        ) {
            val strCaption = context.getResources().getString(R.string.btn_sell)

            val datePickerDialog = DatePickerDialog(
                context,
                DatePickerDialog.OnDateSetListener{ view, year, month, dayOfMonth ->
                    var date = Calendar.getInstance()
                    date.set(Calendar.YEAR, year)
                    date.set(Calendar.MONTH, month)
                    date.set(Calendar.DAY_OF_MONTH, dayOfMonth)
                    sellDate.value = date
                },
                sellDate.value.get(Calendar.YEAR), sellDate.value.get(Calendar.MONTH),sellDate.value.get(
                    Calendar.DAY_OF_MONTH)
            )

            //卖出日期
            item{
                Row(){
                    OutlinedTextField(
                        value = TextFieldValue(text=sdfDate.format(sellDate.value.time)),
                        modifier = Modifier.fillMaxSize().padding(vertical = 4.dp),
                        label = { Text(text =strCaption+ stringResource(id = R.string.text_date)) },
                        trailingIcon = {
                            IconButton(onClick = {datePickerDialog.show() }) {
                                Icon(painter = painterResource(id = R.drawable.ic_btn_date), contentDescription = null)
                            }
                        },
                        onValueChange = {
                            autoData()
                        },
                        maxLines = 1,
                        readOnly = true,
                        singleLine = true,
                    )
                }
            }

            //卖出价格
            item {
                InputItem(
                    textFieldValue = sellPrice,
                    label = strCaption+ stringResource(id = R.string.text_price),
                    keyboardType = KeyboardType.Number,
                    onTextChanged = {
                        sellPrice = it
                        autoData()
                    },
                    modifier = Modifier.fillMaxSize().padding(vertical = 4.dp)
                )
            }
            //卖出数量
            item {
                InputItem(
                    textFieldValue = sellAmount,
                    label = strCaption+ stringResource(id = R.string.text_amount),
                    keyboardType = KeyboardType.Number,
                    onTextChanged = {
                        sellAmount = it
                        autoData()
                    },
                    modifier = Modifier.fillMaxSize().padding(vertical = 4.dp)
                )
            }
            //佣金
            item {
                InputItem(
                    textFieldValue = sellCommission,
                    label = stringResource(id = R.string.stock_commission),
                    keyboardType = KeyboardType.Number,
                    onTextChanged = { sellCommission = it },
                    modifier = Modifier.fillMaxSize().padding(vertical = 4.dp)
                )
            }
            //过户费
            item {
                InputItem(
                    textFieldValue = sellTransfer,
                    label = stringResource(id = R.string.stock_transfer),
                    keyboardType = KeyboardType.Number,
                    onTextChanged = { sellTransfer = it },
                    modifier = Modifier.fillMaxSize().padding(vertical = 4.dp)
                )
            }
            //印花税
            item {
                InputItem(
                    textFieldValue = sellTax,
                    label = stringResource(id = R.string.stock_stamp_tax),
                    keyboardType = KeyboardType.Number,
                    onTextChanged = { sellTax = it },
                    modifier = Modifier.fillMaxSize().padding(vertical = 4.dp)
                )
            }
            //红利税
            item {
                InputItem(
                    textFieldValue = bonusTax,
                    label = stringResource(id = R.string.stock_bonus_tax),
                    keyboardType = KeyboardType.Number,
                    onTextChanged = { bonusTax = it },
                    modifier = Modifier.fillMaxSize().padding(vertical = 4.dp)
                )
            }
            item {
                Row(modifier = Modifier.padding(top = 8.dp)){
                    //取消
                    Button(
                        onClick = {
                            handleStatus.value = StockHandleType.Detail
                        },
                        colors = ButtonDefaults.buttonColors(
                            backgroundColor = cancelColor,
                            contentColor = Color.White
                        ),
                        modifier = Modifier.weight(1f).padding(horizontal = 8.dp)

                    ) {
                        Text(
                            text = stringResource(id = R.string.btn_cancel),
                            color = MaterialTheme.colors.onPrimary,
                            modifier = Modifier.padding(horizontal = 30.dp, vertical = 8.dp)
                        )
                    }
                    //卖出
                    Button(
                        onClick = {
                            mViewModel.tradeSell(
                                stock = vStock,
                                price = sellPrice.text.toFloat(),
                                amount = sellAmount.text.toInt(),
                                date = sellDate.value,
                                commission = sellCommission.text.toFloat(),
                                transfer = sellTransfer.text.toFloat(),
                                tax = sellTax.text.toFloat(),
                                btax = bonusTax.text.toFloat()
                            )
                        },
                        modifier = Modifier.weight(1f).padding(horizontal = 8.dp)
                    ) {
                        Text(
                            text = strCaption,
                            color = MaterialTheme.colors.onPrimary,
                            modifier = Modifier.padding(horizontal = 30.dp, vertical = 8.dp)
                        )
                    }
                }

            }
        }
    }

}

/**
 * 股票分红
 */
@Composable
fun StockBonusContent(handleStatus: MutableState<String>, vStock: Stock){
    val mViewModel: TradeViewModel = viewModel()
    val c = Calendar.getInstance()
    var bonusDate = remember { mutableStateOf(c) }
    var bonusMoney by remember { mutableStateOf(TextFieldValue("0")) }
    var bonusAmount by remember { mutableStateOf(TextFieldValue("0")) }
    val sdfDate = SimpleDateFormat("yyyy 年 MM 月 dd 日")
    val context = LocalContext.current
    val stocks = mViewModel.finished.observeAsState(false)
    if(stocks.value){
        handleStatus.value = StockHandleType.Detail
        mViewModel.finishReset()
    }else{
        LazyColumn(
            modifier = Modifier.fillMaxSize().padding(16.dp)
        ) {

            val datePickerDialog = DatePickerDialog(
                context,
                DatePickerDialog.OnDateSetListener{ view, year, month, dayOfMonth ->
                    var date = Calendar.getInstance()
                    date.set(Calendar.YEAR, year)
                    date.set(Calendar.MONTH, month)
                    date.set(Calendar.DAY_OF_MONTH, dayOfMonth)
                    bonusDate.value = date
                },
                bonusDate.value.get(Calendar.YEAR), bonusDate.value.get(Calendar.MONTH),bonusDate.value.get(
                    Calendar.DAY_OF_MONTH)
            )

            //分红除权日期
            item{
                Row(){
                    OutlinedTextField(
                        value = TextFieldValue(text=sdfDate.format(bonusDate.value.time)),
                        modifier = Modifier.fillMaxSize().padding(vertical = 4.dp),
                        label = { Text(text =stringResource(id = R.string.text_deprive)) },
                        trailingIcon = {
                            IconButton(onClick = {datePickerDialog.show() }) {
                                Icon(painter = painterResource(id = R.drawable.ic_btn_date), contentDescription = null)
                            }
                        },
                        onValueChange = {},
                        maxLines = 1,
                        readOnly = true,
                        singleLine = true,
                    )
                }
            }

            //10派X元
            item {
                InputItem(
                    textFieldValue = bonusMoney,
                    label = stringResource(id = R.string.bonus_money),
                    keyboardType = KeyboardType.Number,
                    onTextChanged = { bonusMoney = it },
                    modifier = Modifier.fillMaxSize().padding(vertical = 4.dp)
                )
            }
            //10派X股
            item {
                InputItem(
                    textFieldValue = bonusAmount,
                    label = stringResource(id = R.string.bonus_amount),
                    keyboardType = KeyboardType.Number,
                    onTextChanged = { bonusAmount = it },
                    modifier = Modifier.fillMaxSize().padding(vertical = 4.dp)
                )
            }
            item {
                Row(modifier = Modifier.padding(top = 8.dp)){
                    //取消
                    Button(
                        onClick = {
                            handleStatus.value = StockHandleType.Detail
                        },
                        colors = ButtonDefaults.buttonColors(
                            backgroundColor = cancelColor,
                            contentColor = Color.White
                        ),
                        modifier = Modifier.weight(1f).padding(horizontal = 8.dp)

                    ) {
                        Text(
                            text = stringResource(id = R.string.btn_cancel),
                            color = MaterialTheme.colors.onPrimary,
                            modifier = Modifier.padding(horizontal = 30.dp, vertical = 8.dp)
                        )
                    }
                    //分红
                    /**
                     * stock: Stock, money: Float, amount: Int, date: Calendar
                     */
                    Button(
                        onClick = {
                            mViewModel.stockBonus(
                                stock = vStock,
                                money = bonusMoney.text.toFloat(),
                                amount = bonusAmount.text.toInt(),
                                date = bonusDate.value,
                            )
                        },
                        modifier = Modifier.weight(1f).padding(horizontal = 8.dp)
                    ) {
                        Text(
                            text = stringResource(id = R.string.btn_bonus),
                            color = MaterialTheme.colors.onPrimary,
                            modifier = Modifier.padding(horizontal = 30.dp, vertical = 8.dp)
                        )
                    }
                }

            }
        }
    }
}